package com.mes.handler.plan;

import com.mes.plan.data.EmespPlanOrder;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.openbravo.base.exception.OBException;
import org.openbravo.client.kernel.BaseActionHandler;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.database.SessionInfo;
import org.openbravo.model.ad.access.User;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

/**
 * 计划订单下发
 * @author zt
 */
public class PlanOrderSplitIssuedHandler extends BaseActionHandler {
	private Logger logger = Logger.getLogger(this.getClass());

	@Override
	protected JSONObject execute(Map<String, Object> parameters, String data) {
		JSONObject jsonRep = new JSONObject();
		try {
			OBContext.setAdminMode();
			JSONObject jsonData = new JSONObject(data);
			String id = jsonData.getString("id");
			BigDecimal qty = new BigDecimal(jsonData.getString("qty"));

			EmespPlanOrder planOrder = OBDal.getInstance().get(EmespPlanOrder.class, id);
			User user = OBDal.getInstance().get(User.class, SessionInfo.getUserId());

			planOrder.setStatus("RELEASE");//状态修改为已下发
			planOrder.setCheckDate(new Date());
			planOrder.setCheckUser(user);

			OBDal.getInstance().save(planOrder);
			PlanOrderIssuedHandler handler = new PlanOrderIssuedHandler();

			BigDecimal sumQty = planOrder.getQty();
			BigDecimal subQty = new BigDecimal(0);
			while (subQty.doubleValue() < sumQty.doubleValue()) {
				if (sumQty.subtract(subQty).doubleValue() < qty.doubleValue()) {
					qty = sumQty.subtract(subQty);
				}
				handler.createManuOrder(planOrder, qty);
				subQty = subQty.add(qty);
			}
			jsonRep.put("result", true);
			jsonRep.put("msg", "分解成功！");

			OBDal.getInstance().commitAndClose();
		} catch (Exception e) {
			OBDal.getInstance().rollbackAndClose();
			e.printStackTrace();
			logger.error("计划订单下发：", e);
			try {
				jsonRep.put("result", false);
				jsonRep.put("msg", "处理失败！");
			} catch (JSONException e1) {
			}
			throw new OBException(e);
		} finally {
			OBContext.restorePreviousMode();
		}
		return jsonRep;
	}
}
